// pages/pay/index.js
import { request, showToast } from '../../request/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: '',
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  //点击支付
  async handlePay() {
    try {
      let token = wx.getStorageSync("token");
      //判断是否有token
      if (!token) {
        wx.navigateTo({
          url: '/pages/auth/index',
        });
        return
      }
      //创建订单
      // const header = { Authorization: token };
      let order_price = this.data.totalPrice + '';
      let consignee_addr = this.data.address.provinceName + this.data.address.cityName + this.data.address.countyName + this.data.address.detailInfo;
      const cart = this.data.cart;
      let goods = [];
      cart.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_number: v.goods_num,
        goods_price: v.goods_price
      }));
      const orderParams = { order_price, consignee_addr, goods };
      //发送请求 创建订单 获取订单号
      const { order_number } = await request({ url: "/my/orders/create", data: orderParams, method: "post" });
      //发起预支付
      const { pay } = await request({ url: "/my/orders/req_unifiedorder", data: { order_number }, method: "post" });
      //发起微信支付 requestPayment zuobul
      //查看订单支付状态
      const res = await request({ url: "/my/orders/chkOrder", method: "post", data: { order_number } })
      // console.log(order_number, pay, res);
      await showToast({ title: "支付成功" });
      //支付成功后删除
      let newCart = wx.getStorageSync("cart");
      newCart = newCart.filter(v => !v.checked);
      wx.setStorageSync("cart", newCart)
      //支付成功后跳转
      wx.redirectTo({
        url: '/pages/order/index',
      });
    } catch (error) {
      await showToast({ title: "支付失败" });
      console.log(error);
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // let pages = getCurrentPages();
    // console.log(pages);
    // const { buy } = pages[pages.length - 1].options;
    let address = wx.getStorageSync("address");
    let cart = wx.getStorageSync("cart");
    // let quickBuy = wx.getStorageSync("quickBuy");
    // if (buy === 1) {
    //   cart = quickBuy;
    // } else {}
    //筛选后的数据
    cart = cart.filter(v => v.checked);
    
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(item => {
      totalNum += item.goods_num;
      totalPrice += item.goods_price * item.goods_num
    });
    this.setData({
      cart,
      totalNum,
      totalPrice,
      address
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
})